<?php


class Role extends AdminBase
{

	//角色列表
	public function index(){
		$data['list']=$this->db->get('role')->result_array();
		$this->load->view('role/index',$data);
	}


    
    public function password(){
    		if ($this->post()){
    		$post=$this->input->post();
    		$id=(int)$_SESSION['userinfo']['id'];
    		$data['password']=md5($post['password'].'yw');
    	    $res=$this->db->update('admin', $data,array('id'=>$id));
			if ($res){
				$this->show(['code'=>1,'msg'=>'更新成功']);
			}else{
				$this->show(['code'=>0,'msg'=>'更新失败']);
			}		
    		}
    	
    	$this->load->view('role/password');
    }
    
    
    
	//添加角色
	public function add(){
		if ($this->post()){
			$post=$this->input->post();
			if($this->check($post['name'])){
				$this->show(['code'=>0,'msg'=>'该角色已存在']);
			}
			if (empty($post['authority'])){
				$this->show(['code'=>0,'msg'=>'权限没有选择']);
			}
			$post['authority']=json_encode($post['authority']);
			$post['update_time']=time();
			$post['create_time']=time();
			$res=$this->db->insert('role', $post);
			if ($res){
				$this->show(['code'=>1,'msg'=>'添加成功']);
			}else{
				$this->show(['code'=>0,'msg'=>'添加失败']);
			}
		}
		$data['menu']=$this->GetMenu();
		$this->load->view('role/add',$data);
	}

	//编辑角色
	public function edit(){
		if ($this->post()){
			$post=$this->input->post();
			if (empty($post['authority'])){
				$this->show(['code'=>0,'msg'=>'权限没有选择']);
			}
			$post['authority']=json_encode($post['authority']);
			$post['update_time']=time();
			$res=$this->db->replace('role', $post);
			if ($res){
				$this->show(['code'=>1,'msg'=>'更新成功']);
			}else{
				$this->show(['code'=>0,'msg'=>'更新失败']);
			}
		}

		$id=$this->GetId();
		$data['list']=$this->db->where('id',$id)->get('role')->row_array();
		$data['menu']=$this->GetMenu();
		$this->load->view('role/edit',$data);
	}

	//删除角色
	public function del(){
		$id=$this->PostId();
		if ($this->checkadmin($id)){
			$this->show(['code'=>0,'msg'=>'无法删除,该角色存在管理员']);
		}
		$res=$this->db->delete('role', array('id'=>$id));
		if ($res){
			$this->show(['code'=>1,'msg'=>'删除成功']);
		}else{
			$this->show(['code'=>0,'msg'=>'删除失败']);
		}
	}

	//检查角色是否存在
	public function check($name){
		$check=$this->db->where('name',$name)->get('role')->row_array();
		if ($check){
			return  true;
		}else{
			return  false;
		}
	}

	//检查角色是否存在管理员
	public function checkadmin($role_id){
		$check=$this->db->where('role_id',$role_id)->get('admin')->row_array();
		if (!is_null($check)){
			return  true;
		}else{
			return false;
		}
	}


}
